package com.etlmaster.executor.steps.table;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.processors.Table.CreateTableFromPropertyProcessor;
import com.etlmaster.executor.processors.Table.CreateTableMeta;
import com.etlmaster.executor.processors.Table.CreateTableProcessor;
import com.etlmaster.executor.processors.Table.RationalDbProcessor;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.StepState;

/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("crtTab")
public class CreateTableStep extends Step {

	private CreateTableStepMeta meta;

	private String dsType;
	public CreateTableStep(StepMeta meta) {
		super(meta);
		this.meta = (CreateTableStepMeta) meta;
	}

	@Override
	protected int handle() {

		try{
			dsType = DataCollectionUtils.getDsType(
				meta.getDsName());
		}catch(Exception e){
			meta.log("ERROR","获取数据库类型失败");
			return StepState.RUNNING_FAILED;
		}

		Map<String,Object> data=new HashMap<String,Object>();
		data.putAll(meta.getVariables());
		if(meta.getExtraParam()!=null)
			data.putAll(meta.getExtraParam());
		CreateTableMeta tablemeta=new CreateTableMeta(meta.getTableName(),meta.getXmlId(),dsType,meta.getVariable("taskid").toString(),meta.getOverride());
		
		tablemeta.setMetaTableName(meta.getMetaTableName());
		tablemeta.setXmlId(meta.getXmlId());
		String result="";
		CreateTableProcessor processor;
		if (isDdlFromFile()) {
			processor=new CreateTableFromPropertyProcessor();
			result= processor.process(tablemeta,data);
		}else {
			processor=new RationalDbProcessor();
			result= processor.process(tablemeta,data);
		}
		meta.getStepState().getReturnValue().put("ddl", processor.getDdl());
		if(result.equals(StepState.RUNNING_SUCCESSED+"")){
			return StepState.RUNNING_SUCCESSED;
		}else{
			meta.getStepState().getReturnValue().put("errorMessage", result);
			return StepState.RUNNING_FAILED;
		}
		
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
	
	public boolean isDdlFromFile(){
		
		String[] dbArray=DataCollectionUtils.getProperties("tableDDlList").split(",");
		List dblist=Arrays.asList(dbArray);
		return dblist.contains(dsType);
	}

}
